import {Client, StompSubscription} from "@stomp/stompjs";
import AlertService from "@/components/Global/Alert/service";
import {
    FriendOfflinePayload,
    FriendOnlinePayload,
    NoticeMessage,
    SystemAnnouncementPayload,
} from "@/types/stomp/notice";
import FriendsStateStore from "@/store/friend";
import {FriendStatus} from "@/types/friend";
import {OnlineSystemMessage} from "@/types/stomp/system";
import MessageOperationContext from "@/services/stomp/stomp-message-handler";
import WebRTCStateStore from "@/store/webrtc";
import {SignalMessageResponse, SignalType} from "@/types/webrtc";
import {router} from "expo-router";
import {MessageOperation} from "@/types/stomp";

// 系统通知订阅频道
const SYSTEM_NOTICE_SUBSCRIBE_CHANNEL = "/user/system/notice";
// 聊天消息订阅频道
const CHAT_SUBSCRIBE_CHANNEL = "/user/chat/message";
// 错误信息订阅频道
const ERROR_SUBSCRIBE_CHANNEL = "/user/system/errors";
// WebRTC通知订阅频道
const WEBRTC_NOTICE_SUBSCRIBE_CHANNEL = "/user/webrtc/notice";

const subscribeWebSocketChannel = (stompClient: Client) => {
    const subscriptions: StompSubscription[] = [];
    const {updateFriend} = FriendsStateStore.getState().actions;
    const webrtcActions = WebRTCStateStore.getState().actions

    function subscribeSystemChannel() {
        const sub = stompClient.subscribe(
            SYSTEM_NOTICE_SUBSCRIBE_CHANNEL,
            (message) => {
                const noticeMessage = JSON.parse(message.body) as NoticeMessage<any>;
                console.log("[STOMP] Received SYSTEM message:", noticeMessage);
                switch (noticeMessage.type) {
                    case 1:
                        const onlineNotice =
                            noticeMessage as NoticeMessage<FriendOnlinePayload>;
                        updateFriend({
                            friendId: onlineNotice.payload.friendId,
                            friendStatus: FriendStatus.ONLINE,
                        });
                        break;
                    case 2:
                        const offlineNotice =
                            noticeMessage as NoticeMessage<FriendOfflinePayload>;
                        updateFriend({
                            friendId: offlineNotice.payload.friendId,
                            friendStatus: FriendStatus.OFFLINE,
                            lastOnlineTime: offlineNotice.payload.offlineTime,
                        });
                        break;
                    case 3:
                        const systemNotice =
                            noticeMessage as NoticeMessage<SystemAnnouncementPayload>;
                        AlertService.showAlert("info", systemNotice.payload.content);
                        break;
                }
            }
        );
        subscriptions.push(sub);
        return sub;
    }

    function subscribeChatMessageChannel() {
        const sub = stompClient.subscribe(
            CHAT_SUBSCRIBE_CHANNEL,
            async (message) => {
                const data = JSON.parse(message.body);
                console.log("[STOMP] Received CHAT message:", data);
                console.log("data.operation:", data.operation);
                const strategy = MessageOperationContext.getStrategy(data.operation as MessageOperation);
                console.log("[STOMP] Using strategy:", strategy);
                strategy.execute(message);
            }
        );
        subscriptions.push(sub);
        return sub;
    }

    function subscribeErrorChannel() {
        const sub = stompClient.subscribe(ERROR_SUBSCRIBE_CHANNEL, (message) => {
            const systemMessage: OnlineSystemMessage = JSON.parse(
                message.body
            ) as OnlineSystemMessage;
            AlertService.showAlert("error", systemMessage.message);
        });
        subscriptions.push(sub);
        return sub;
    }


    function subscribeWebRTCNoticeChannel() {
        const sub = stompClient.subscribe(WEBRTC_NOTICE_SUBSCRIBE_CHANNEL, async (message) => {
            console.log("[STOMP] Received WEBRTC message:", message.body);
            const signalMsgResp = JSON.parse(message.body) as SignalMessageResponse;

            if (signalMsgResp.type === SignalType.OFFER) {
                // 1. 更新 store 状态（设置当前来电信令）
                webrtcActions.setCurrentCall(signalMsgResp);

                // 2. 跳转到通话页面，传入对方用户信息参数
                router.push({
                    pathname: "/call/video-realtime-call",
                    params: {
                        id: signalMsgResp.user.id,
                        name: signalMsgResp.user.name,
                        avatar: signalMsgResp.user.avatar,
                        updateTime: signalMsgResp.user.updateTime,
                    },
                });
            }
        });
        subscriptions.push(sub);
        return sub;
    }

    subscribeSystemChannel();
    subscribeChatMessageChannel();
    subscribeErrorChannel();
    subscribeWebRTCNoticeChannel();
    // 返回所有订阅，便于管理
    return subscriptions;
};

class StompSubscriptionManager {
    private subscriptions: StompSubscription[] = [];

    setUpSubscriptions(client: Client) {
        this.unsubscribeAll(); // 清除之前的订阅
        this.subscriptions = subscribeWebSocketChannel(client); // 重新设置订阅
    }

    addSubscription(subscription: StompSubscription) {
        this.subscriptions.push(subscription);
    }

    unsubscribeAll() {
        this.subscriptions.forEach((sub) => sub.unsubscribe());
        this.subscriptions = [];
    }
}

export default StompSubscriptionManager;
